#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "LogMessage.hpp"

void Usage()
{
    std::cout << "Please enter: ./Client ip port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        return 4;
    }
    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);

    Log lg;
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        lg.LogMessage(Error, "create socket error");
        exit(1);
    }
    lg.LogMessage(Normal, "create socket success, socket:%d", sockfd);

    sockaddr_in addr;
    socklen_t addrlen = sizeof(addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    if (connect(sockfd, (sockaddr *)&addr, addrlen) < 0)
    {
        lg.LogMessage(Error, "connect error");
        exit(2);
    }
    lg.LogMessage(Normal, "connect success");

    // 先接受服务端的消息
    char temp[128];
    sockaddr_in raddr;
    socklen_t raddrlen = sizeof(addr);
    int n = recvfrom(sockfd, temp, sizeof(temp) - 1, 0, (sockaddr *)&raddr, &raddrlen);
    if (n <= 0)
    {
        std::cout << "recvfrom error" << std::endl;
        exit(3);
    }
    temp[n] = 0;
    std::cout << temp << std::endl;

    // 向服务端发送你想要执行的服务
    std::string buffer;
    std::cout << "Please enter# " << std::endl;
    getline(std::cin, buffer);
    sendto(sockfd, buffer.c_str(), buffer.size(), 0, (sockaddr *)&addr, addrlen);

    std::cout << "Please enter you message: " << std::endl;
    getline(std::cin, buffer);
    sendto(sockfd, buffer.c_str(), buffer.size(), 0, (sockaddr *)&addr, addrlen);

    raddrlen = sizeof(addr);
    n = recvfrom(sockfd, temp, sizeof(temp) - 1, 0, (sockaddr *)&raddr, &raddrlen);
    if (n > 0)
    {
        temp[n] = 0;
        std::cout << temp << std::endl;
    }

    return 0;
}